home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 8753 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.2 KB  |  65 lines

  1. Path: news.th-darmstadt.de!news
  2. From: Enno Sandner <enno@intellektik.informatik.th-darmstadt.de>
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Deleting Data Members that are Const Pointers / References?
  5. Date: Mon, 26 Feb 1996 15:41:16 +0100
  6. Organization: Fachbereich Informatik, TH Darmstadt
  7. Message-ID: <3131C68C.446B9B3D@intellektik.informatik.th-darmstadt.de>
  8. References: <4groo7$4bt@radmail.rad.co.il>
  9. NNTP-Posting-Host: kitz.intellektik.informatik.th-darmstadt.de
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=us-ascii
  12. Content-Transfer-Encoding: 7bit
  13. X-Mailer: Mozilla 2.0 (X11; I; SunOS 4.1.3 sun4m)
  14.  
  15. udi wrote:
  16. > news:comp.lang.c++#pvcybpuqx6p.fsf@hln56.pki-nbg.philips.de
  17. > Hi everybody,
  18. > I have a simple question regarding data members that are
  19. > constant pointers or references.
  20. > Let's say I have a class Foo that has a data member xr (say of type int&
  21. > - in reality a different type) that is a constant reference. Objects of
  22. > class Foo must have an instance of xr during their lifetime, that's a
  23. > reason to have xr a reference. Also, xr must not change (not even
  24. > accidentaly, by some member function / friend of Foo), that's why I want
  25. > xr to be constant.Foo is always initialized with an int that was
  26. > allocated off the heap, but xr should cease to exist when Foo does, so
  27. > Foo is responsible to destroy xr and free the memory occupied by it.
  28. > However, deleting a const reference (pointer) is not allowed (at least
  29. > according to Borland 4.5 and g++). This seems logical as the operand to
  30. > delete is a void* and the compiler says he can't convert a const int* to
  31. > a void*.
  32. > So, THE QUESTION IS:
  33. > Is there an alternative to brutally casting the const away?
  34. > A sample code:
  35. > class Foo [
  36. > public:
  37. >    Foo(const int& xr1) : xr(xr1) {}
  38. >    ~Foo() [ delete &xr; ] // ERROR - attempt to delete a constant pointer
  39. > private:
  40. >    int& xr;
  41. > ];
  42. > int main() {
  43. > int& xr1 = *(new int(100));
  44. > Foo* fooP = new Foo(xr1);
  45. > //...
  46. > delete fooP;
  47. > }
  48. > Alternative:
  49. > ~Foo() [ delete (int*)(&xr); ] // BRUTAL CASTING
  50.  
  51. The casting hack works but is no longer necessary.
  52. According to the DWP you can delete a 'const'-object.
  53. Check out for a newer version of 'g++'. For instance
  54. g++ 2.7.2 doesn't complain about deleting a const-object.
  55.  
  56.     Enno
  57.